package com.pinghua.mocha.basics;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author: songkui
 * @since : 2021/2/23 15:17
 */
public class NumberKits extends NumberUtil {

    public static long parseLong(String number, long defaultValue) {
         try {
             return parseLong(number);
         }catch (Exception e){
             return defaultValue;
         }
    }

    public static boolean isMinus(Number number){
        return null == number || number.longValue() < 1 ? true : false;
    }

    public static boolean isNotMinus(Number number){
        return !isMinus(number);
    }

    /**
     * 0：表示前面补0
     * digit：表示保留数字位数
     * d：表示参数为正数类型
     */
    public static String fillString(int num , int digit, String prefix) {
        return String.format("%0"+digit+"d", num);
    }


    public static BigDecimal div(String v1, String v2, int scale, RoundingMode roundingMode, BigDecimal defaultValue) {
        if (StrUtil.isEmpty(v2) || isZeroTolerant(v2)){
            return defaultValue;
        }

        return div(toBigDecimal(v1), toBigDecimal(v2), scale, roundingMode);
    }
    public static BigDecimal div(String v1, String v2, int scale, RoundingMode roundingMode, BigDecimal defaultValue, BigDecimal maxValue) {
        if (StrUtil.isEmpty(v2) || isZeroTolerant(v2)){
            return defaultValue;
        }
        BigDecimal bigDecimal = div(toBigDecimal(v1), toBigDecimal(v2), scale, roundingMode);
        return bigDecimal.compareTo(BigDecimal.ONE) > 0 ? maxValue : bigDecimal;
    }
    public static BigDecimal div(Number v1, Number v2, int scale, RoundingMode roundingMode, BigDecimal defaultValue, BigDecimal maxValue) {
        if (null == v2 || isZeroTolerant(String.valueOf(v2))){
            return defaultValue;
        }
        BigDecimal bigDecimal = div(v1, v2, scale, roundingMode);
        return bigDecimal.compareTo(BigDecimal.ONE) > 0 ? maxValue : bigDecimal;
    }

    public static boolean isZeroTolerant(String str) {
        if (str == null || str.isEmpty()) return false;
        try {
            String cleanStr = str.trim()
                    .replaceAll(",", "")      // 移除千分位逗号
                    .replaceAll("[^\\d.Ee+-]", ""); // 移除非数字字符
            double num = Double.parseDouble(cleanStr);
            return Math.abs(num) < 1e-10; // 处理浮点精度误差
        } catch (NumberFormatException e) {
            return false;
        }
    }


}
